package com.xj.common.sdk.api;

import com.alibaba.fastjson.JSONObject;
import com.xj.common.bean.R;
import com.xj.common.bean.constant.Common;
import com.xj.common.model.Device;
import com.xj.common.sdk.bean.command.CmdParameter;
import com.xj.common.sdk.service.DriverCommandService;
import com.xj.common.utils.JsonPaseUtil;
import com.xj.common.valid.ValidatableList;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;

/**
 *驱动命令对外暴露接口
 * @author wsp
 *
 */
@RestController
@RequestMapping(value = Common.Service.IE_DATA_REAL)
public class DriverCommandAPI {

	@Resource
	private DriverCommandService driverCommandService;

	@RequestMapping(value = Common.Service.IE_SDK_DRIVER_GETPOINT,method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	@CrossOrigin
	public Object handleReadPoint(
			@RequestBody JSONObject jsonParam
			) throws IOException
	{


		return null;
	}

	@RequestMapping(value = Common.Service.IE_SDK_DRIVER_WRITEPOINT,method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	@CrossOrigin
	public Object handleWritePoint(
			@RequestBody JSONObject jsonParam
	) throws IOException
	{
		ValidatableList<CmdParameter> cmdParameters = JsonPaseUtil.JSONStrToList(jsonParam.getJSONArray("Points").toJSONString(),CmdParameter.class);
		try {
			if (cmdParameters.size() > Common.Driver.MAX_REQUEST_SIZE) {
				return R.fail("point request size are limited to " + Common.Driver.MAX_REQUEST_SIZE);
			}
			cmdParameters.forEach(cmdParameter -> driverCommandService.write(cmdParameter.getDeviceId(), cmdParameter.getPointId(), cmdParameter.getValue()));
		} catch (Exception e) {
			return R.fail(e.getMessage());
		}
		return R.ok();

	}
}
